import React, { useState } from 'react';
import { Card, Typography, Button, Progress, Empty, message, Modal, Spin, Alert } from 'antd';
import { DownloadOutlined, ReloadOutlined, FullscreenOutlined, ShareAltOutlined, CopyOutlined } from '@ant-design/icons';
import './ImageResult.css';

const { Title, Text } = Typography;

const ImageResult = ({ resultImage, isGenerating, progress, error, onRetry }) => {
  const [previewVisible, setPreviewVisible] = useState(false);
  const [downloading, setDownloading] = useState(false);

  // 处理图片下载
  const handleDownload = () => {
    if (!resultImage) return;
    
    try {
      setDownloading(true);
      // 创建一个临时链接并触发下载
      const link = document.createElement('a');
      link.href = resultImage;
      link.download = `tuling-painter-${new Date().getTime()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('图片下载成功！');
    } catch (err) {
      message.error('下载失败：' + err.message);
    } finally {
      setDownloading(false);
    }
  };

  // 复制图片到剪贴板
  const handleCopy = async () => {
    if (!resultImage) return;
    
    try {
      const response = await fetch(resultImage);
      const blob = await response.blob();
      await navigator.clipboard.write([
        new ClipboardItem({
          [blob.type]: blob
        })
      ]);
      message.success('图片已复制到剪贴板');
    } catch (err) {
      message.error('复制失败：' + err.message);
    }
  };

  // 分享图片（这里只是模拟）
  const handleShare = () => {
    if (!resultImage) return;
    
    if (navigator.share) {
      navigator.share({
        title: '我的AI生成图像',
        text: '查看我用图灵画匠生成的图像',
        url: resultImage
      })
      .then(() => message.success('分享成功'))
      .catch((error) => message.error('分享失败：' + error.message));
    } else {
      message.info('您的浏览器不支持分享功能');
    }
  };

  return (
    <>
      <Card className="result-card">
        <Title level={4} className="result-title">生成结果</Title>
        
        <div className="result-container">
          {isGenerating ? (
            <div className="generating-container">
              <Progress 
                type="circle" 
                percent={progress} 
                status="active"
                strokeColor={{
                  '0%': '#108ee9',
                  '100%': '#87d068',
                }}
              />
              <Text className="generating-text">正在生成图像，请稍候...</Text>
            </div>
          ) : error ? (
            <div className="error-container">
              <Alert
                message="生成失败"
                description={error}
                type="error"
                showIcon
              />
              <Button 
                icon={<ReloadOutlined />} 
                onClick={onRetry}
                type="primary"
                className="retry-button"
              >
                重试
              </Button>
            </div>
          ) : resultImage ? (
            <div className="result-image-container">
              <div className="result-image-wrapper">
                <img 
                  src={resultImage} 
                  alt="生成结果" 
                  className="result-image" 
                  onClick={() => setPreviewVisible(true)}
                />
              </div>
              
              <div className="result-actions">
                <Button 
                  type="primary" 
                  icon={<DownloadOutlined />} 
                  onClick={handleDownload}
                  loading={downloading}
                  className="action-button"
                >
                  下载
                </Button>
                <Button 
                  icon={<FullscreenOutlined />} 
                  onClick={() => setPreviewVisible(true)}
                  className="action-button"
                >
                  查看
                </Button>
                <Button 
                  icon={<CopyOutlined />} 
                  onClick={handleCopy}
                  className="action-button"
                >
                  复制
                </Button>
                <Button 
                  icon={<ShareAltOutlined />} 
                  onClick={handleShare}
                  className="action-button"
                >
                  分享
                </Button>
              </div>
            </div>
          ) : (
            <Empty 
              description="尚未生成图像" 
              image={Empty.PRESENTED_IMAGE_SIMPLE} 
              className="empty-result"
            />
          )}
        </div>
      </Card>
      
      {/* 全屏预览模态框 */}
      <Modal
        open={previewVisible}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
        width="80%"
        centered
        className="preview-modal"
      >
        <img 
          alt="预览" 
          style={{ width: '100%' }} 
          src={resultImage} 
        />
        <div className="preview-modal-actions">
          <Button 
            type="primary" 
            icon={<DownloadOutlined />} 
            onClick={handleDownload}
          >
            下载图像
          </Button>
        </div>
      </Modal>
    </>
  );
};

export default ImageResult;